package org.jiucai.cas.auth.service;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.jiucai.appframework.base.spring.service.BaseService;
import org.jiucai.appframework.common.encrypt.EncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.jiucai.cas.auth.dao.AuthDao;
import org.jiucai.cas.data.Constant;
import org.jiucai.cas.domain.AuthQuery;
import org.jiucai.cas.domain.UserInfo;

@Service("authService")
public class AuthServiceImpl extends BaseService implements AuthService {


	@Autowired
	private AuthDao authDao;

	public void setAuthDao(AuthDao authDao) {
		this.authDao = authDao;
	}

	@Override
	public Boolean checkUser(AuthQuery query) {
		return authDao.checkUser(query);
	}

	@Override
	public UserInfo getUserInfo(AuthQuery query) {

		return authDao.getUserInfo(query);
	}

	@Override
	public UserInfo getUserInfo(UserInfo query) {

		return authDao.getUserInfo(query);
	}

	/**
	 * 检查密钥
	 * 
	 * @param uid
	 * @param ts
	 * @param key
	 * @return
	 */
	@Override
	public String checkKey(Long uid, Long ts, String key) {
		String msg = null;
		String encodeKey = "";

		log.debug("param uid:" + uid);
		log.debug("param ts: " + ts);
		log.debug("param key: " + key);

		long ctm = System.currentTimeMillis();
		if (Math.abs(ctm - ts) / 1000 > Constant.REQ_EXPIRED_TIME) {
			msg = "请求已过期。";
			return msg;
		}

		try {
			String param = String.valueOf(uid) + "|" + String.valueOf(ts);
			encodeKey = EncryptUtil.encrypt(param, Constant.AUTH_STATIC_KEY);
			log.debug("encodeKey: " + encodeKey);
		} catch (Exception e) {
			log.error("Encoding key from: uid: " + uid + " key: " + key
					+ " ts: " + ts);
			log.error("Can not get encode key: "
					+ ExceptionUtils.getFullStackTrace(e));
		}

		if (!encodeKey.equals(key)) {
			msg = "参数不匹配。";
			return msg;
		}

		return msg;

	}

}
